package com.xzq.erp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xzq.erp.context.BaseContext;
import com.xzq.erp.domain.po.SysRolePermission;
import com.xzq.erp.domain.po.SysUser;
import com.xzq.erp.domain.vo.UserRoleVO;
import com.xzq.erp.mapper.SysRolePermissionMapper;
import com.xzq.erp.mapper.SysUserMapper;
import com.xzq.erp.service.ISysRolePermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzq.erp.service.ISysRoleService;
import com.xzq.erp.service.ISysUserRoleService;
import lombok.RequiredArgsConstructor;
import org.assertj.core.util.Lists;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色与权限关联表 服务实现类
 * </p>
 *
 * @author xzq
 * @since 2025-05-19
 */
@Service
@RequiredArgsConstructor
public class SysRolePermissionServiceImpl extends ServiceImpl<SysRolePermissionMapper, SysRolePermission> implements ISysRolePermissionService {

    private final SysUserMapper userMapper;

    private final ISysUserRoleService userRoleService;

    private final ISysRoleService roleService;

    @Override
    public void removeByRoleId(Integer roleId) {
        LambdaQueryWrapper<SysRolePermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRolePermission::getRoleId, roleId);
        this.remove(wrapper);
    }

    @Override
    public List<String> getUserPermissions() {
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        Long userId = BaseContext.getUserId();
        SysUser user = userMapper.selectOne(
                new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getId, userId)
        );
        // 获取权限列表
        List<String> permissions = Lists.newArrayList();
        List<UserRoleVO> userRoleVOList = userRoleService.getUserRoleVOList(Collections.singletonList(user.getId()));
        if(!CollectionUtils.isEmpty(userRoleVOList)){
            for(UserRoleVO userRoleVO : userRoleVOList){
                permissions.add(userRoleVO.getRoleName());
            }
            List<Integer> roleIds = userRoleVOList.stream().map(UserRoleVO::getRoleId).collect(Collectors.toList());
            List<String> roleIdsPermissions = roleService.getRoleIdsPermissions(roleIds);
            permissions.addAll(roleIdsPermissions);
        }
        return permissions;
    }
}
